package servlet;

import com.google.gson.Gson;

import dao.EmpDao;
import entity.Emp;
import org.apache.ibatis.session.SqlSession;
import util.PageUtil;
import util.SqlSessionFactoryUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet("/empPage")
public class EmpPageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        int pageNum=Integer.parseInt(request.getParameter("pageNum"));
        int pageSize=Integer.parseInt(request.getParameter("pageSize"));
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("pageNum",(pageNum-1)*pageSize);
        map.put("pageSize",pageSize);
        SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
        EmpDao empDao= sqlSession.getMapper(EmpDao.class);
        List<Emp> list = empDao.findEmpPage(map);
        //获取全部信息的数量
        int count=empDao.selectEmpCount();
        //获取总页数
        int totalPage= PageUtil.getTotalPages(count,pageSize);
        Gson gson=new Gson();
        Map<String,Object> maps=new HashMap<>();
        maps.put("pageNum",pageNum);
        maps.put("pageSize",pageSize);
        maps.put("totalPage",totalPage);
        maps.put("list",list);
        String json=gson.toJson(maps);
        out.print(json);
        out.flush();
        sqlSession.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
